package com.tmsps.ne4Weixin.api;

import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.tmsps.ne4Weixin.config.WxConfig;

/**
 * 多媒体api
 * 
 * @author L.cm
 */
public class MediaApi extends BaseAPI {

	public MediaApi(WxConfig config) {
		super(config);
	}

	// 文档地址：https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738727&token=&lang=zh_CN
	private static final String getTempMediaUrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s";

	// 获取临时素材
	public void getTempMedia(String media_id, OutputStream out) {
		String url = String.format(getTempMediaUrl, config.getAccessToken(), media_id);

		HttpClient httpclient = new DefaultHttpClient();
		InputStream input = null;
		try {
			HttpGet httpget = new HttpGet(url);
			HttpResponse response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			input = entity.getContent();
			try {
				IOUtils.copy(input, out);
			} finally {
				IOUtils.closeQuietly(out);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(input);
		}

	}

}
